package com.happyscan138.makefun;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.happyscan138.makefun.base.VideoPlayView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.IOException;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

import static com.happyscan138.makefun.base.Uri.getPhotoPathFromContentUri;
import static com.happyscan138.makefun.base.bitmap.getSmallBitmap;
import static com.loopj.android.http.AsyncHttpClient.log;

/**
 * Created by Administrator on 2016/12/20.
 */

public class SpoofAnswer extends AppCompatActivity implements View.OnClickListener, VideoPlayView.MediaPlayerImpl {
    private ImageView back;
    private Button buttonFinish;
    private EditText editTextContent;
    private ImageButton input_file;
    private ImageButton input_voice;
    //惡搞答案文本
    private String SpoofContent;
    private String Path;
    private String VoiceStr;
    private Intent intent;
    private ImageView iamgeView;
    private LayoutInflater inflater;
    private boolean isPlaying;
    private MediaPlayer mediaPlayer;
    private ImageButton Saoku;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.egao_answer);
        initView();
    }
    public void initView(){
        textwacher change=new textwacher();
        inflater = LayoutInflater.from(this);
        back=(ImageView)findViewById(R.id.spoofAnswer_Back);
        back.setOnClickListener(this);
        buttonFinish=(Button)findViewById(R.id.SpoofFinish);
        buttonFinish.setOnClickListener(this);
        editTextContent=(EditText)findViewById(R.id.SpoofText);
        editTextContent.addTextChangedListener(change);
        input_file=(ImageButton)findViewById(R.id.SpoolInputFile);
        input_file.setOnClickListener(this);
        input_voice=(ImageButton)findViewById(R.id.SpoofVoice);
        input_voice.setOnClickListener(this);
        iamgeView=(ImageView)findViewById(R.id.SpoofAnswer_image);
        Saoku=(ImageButton)findViewById(R.id.Saoku_SpoofAnswer);
        Saoku.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.spoofAnswer_Back:
                finish();
                break;
            case R.id.SpoofFinish:
                if(SpoofContent==null){
                    Toast.makeText(SpoofAnswer.this,"请输入恶搞答案文本",Toast.LENGTH_SHORT).show();
                }else if(Path==null){
                    Toast.makeText(SpoofAnswer.this,"请输入恶搞答案信息",Toast.LENGTH_SHORT).show();
                }else if(SpoofContent==null&&Path==null){
                    Toast.makeText(SpoofAnswer.this,"请输入恶搞答案",Toast.LENGTH_SHORT).show();
                }else {
                    Bundle bundle = new Bundle();
                    bundle.putString("spoof_content", SpoofContent);
                    bundle.putString("spoof_imgpath", Path);
                    setResult(002, SpoofAnswer.this.getIntent().putExtras(bundle));
                    this.finish();
                }
                break;
            case R.id.SpoolInputFile:
                intent = new Intent();
                intent.setType("video/*;image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent,  1);
                break;
            case R.id.SpoofVoice:
                startActivityForResult(new Intent(this,Record.class),002);
                break;
            case R.id.Saoku_SpoofAnswer:
                intent =new Intent();
                intent.setClass(SpoofAnswer.this,Saoku.class);
                startActivityForResult(intent,050);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
            Uri uri = data.getData();
            Path=uri.toString();
            log.e("pathSpoof",Path);
            if(Path.endsWith(".jpg")||Path.endsWith(".png")){
                uri = geturi(data);//解决方案
                Path = path(uri);
                iamgeView.setImageBitmap(getSmallBitmap(path(uri)));
            }else if(Path.endsWith(".mp4")){//如果返回的视频文件，布局进行切换
                Path=getPhotoPathFromContentUri(this,uri);
                LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.saoku_video_item, null);
                replaceVieo(Path,layout);
                LinearLayout linearLayout = (LinearLayout) findViewById(R.id.SpoofAnswer_Dynamic);
                linearLayout.removeView(findViewById(R.id.SpoofAnswer_image));
                linearLayout.addView(layout);
            }

        }
        if (requestCode==002&&resultCode==011&&data!=null){
            Bundle bundle=data.getExtras();
            VoiceStr=bundle.getString("Voice_Path");
            if (VoiceStr.endsWith(".mp3")) {
                LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dynamic_voice_a, null);
                LinearLayout linearLayout = (LinearLayout) findViewById(R.id.SpoofAnswer_Dynamic);
                linearLayout.removeView(findViewById(R.id.SpoofAnswer_image));
                linearLayout.addView(layout);
                ImageButton QuestionPlay=(ImageButton)layout.findViewById(R.id.Dymanic_play_voice_A);
                mediaPlayer=new MediaPlayer();
                try {
                    mediaPlayer.setDataSource(VoiceStr);
                    mediaPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                QuestionPlay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mediaPlayer.start();
                    }
                });
            }
        }
        if(requestCode==050&&resultCode==1&&data!=null){
            Bundle bundle = data.getExtras();
            String a=bundle.getString("SaokuText");
            String b=bundle.getString("SaokuImg");
            String video=bundle.getString("SaokuVideo");
            String Gif=bundle.getString("SaokuGif");
            log.e("gifAnswerA",Gif);
            if(a!=null){
                editTextContent.setText(a);
                SpoofContent=a;
            }else if(b!=null){
                String path=b.substring(28);
                Path=path;
                Picasso.with(SpoofAnswer.this).load(b).into(iamgeView);
            }else if(video!=null){
                log.e("video",video);
                LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.saoku_video_item, null);
                replaceVieo(video,layout);
                LinearLayout linearLayout = (LinearLayout) findViewById(R.id.SpoofAnswer_Dynamic);
                linearLayout.removeView(findViewById(R.id.SpoofAnswer_image));
                linearLayout.addView(layout);
                Path=video.substring(28);

            }else if(Gif!=null){

                LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.gif_item, null);
                GifImageView gifImageView=(GifImageView) layout.findViewById(R.id.info_gif1_A);
                File saveImgPath = getImageDir(this);
                File gifSavePath1 = new File(saveImgPath, "gif1");
                displayImage(Gif, gifSavePath1, gifImageView);

                LinearLayout linearLayout = (LinearLayout) findViewById(R.id.SpoofAnswer_Dynamic);
                linearLayout.removeView(findViewById(R.id.SpoofAnswer_image));
                linearLayout.addView(layout);

                Path=Gif.substring(28);
                log.e("SaokuResource",Path);
            }
        }
    }
    public Uri geturi(Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[] { MediaStore.Images.ImageColumns._ID },
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }


        return uri;
    }
    private String path(Uri uri ) {

        String path = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, proj, null, null, null);
        log.e("cursor", cursor.toString());
        if (cursor != null) {
            ContentResolver cr = this.getContentResolver();
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            path = cursor.getString(column_index);// 图片在的路径
            log.e("path",path);
        }
        return path;

    }

    @Override
    public void onError() {

    }

    @Override
    public void onExpend() {

    }

    @Override
    public void onShrik() {

    }

    class textwacher implements TextWatcher{

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            SpoofContent=editTextContent.getText().toString();
        }
    }
    private void replaceVieo(final String path,LinearLayout layout){
        ImageView play=(ImageView)layout.findViewById(R.id.saoku_play_btn);
        final VideoPlayView playView=(VideoPlayView)layout.findViewById(R.id.saoku_video_play_view);
        final FrameLayout showLayout=(FrameLayout)layout.findViewById(R.id.saoku_show_layout);
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isPlaying = true;
                showLayout.setVisibility(View.GONE);
                playView.setUrl(path);
                setPlayView(playView);
                playView.openVideo();
                playView.setVisibility(View.VISIBLE);
            }
        });
    }
    public void setPlayView(VideoPlayView playView) {
        playView.setMediaPlayerListenr(this);
    }
    public File getImageDir(Context context){
        File file = getFilesDir(context, "images");
        return file;
    }
    public File getFilesDir(Context context, String tag){
        if(isSdCardExist() == true){
            return context.getExternalFilesDir(tag);
        }
        else{
            return context.getFilesDir();
        }
    }
    public boolean isSdCardExist() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }
    public void displayImage(String url, File saveFile, final GifImageView gifView){
        HttpUtils http = new HttpUtils();
        // 下载图片
        http.download(url, saveFile.getAbsolutePath(), new RequestCallBack<File>() {
            public void onSuccess(ResponseInfo<File> responseInfo) {
                try {
                    Log.e("tag", "onSuccess========" + responseInfo.result.getAbsolutePath());
                    GifDrawable gifFrom = new GifDrawable( responseInfo.result.getAbsolutePath() );
                    gifView.setImageDrawable(gifFrom);
                }
                catch(Exception e){
                    Log.e("tag", e.getMessage());
                }
            }

            @Override
            public void onFailure(com.lidroid.xutils.exception.HttpException e, String s) {
                Log.e("tag", "onFailure========" + s);
            }});
    }
}

